package com.qboot.common.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.qboot.common.annotation.Log;
import com.qboot.common.consts.CommonConst;
import com.qboot.common.consts.MsgConst;
import com.qboot.common.entity.Result;
import com.qboot.common.exception.BusinessException;
import com.qboot.common.utils.AssertUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 *
 * @author Tellsea
 * @date 2022/12/27
 */
@Api(tags = "文件")
@RestController
@RequestMapping("/common/file")
public class FileController {

    @ApiOperation("文件上传")
    @Log("文件上传")
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        AssertUtils.isTrue(file.isEmpty(), "文件不能为空");
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffixName;
        String dateFolder = DateUtil.format(DateUtil.date(), "/yyyy/MM/dd/");
        File dest = new File(CommonConst.UPLOAD_PATH + dateFolder + fileName);
        FileUtil.mkParentDirs(dest);
        try {
            file.transferTo(dest);
            return Result.ok(MsgConst.UPLOAD_SUCCESS, CommonConst.FILE_PREFIX + dateFolder + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(MsgConst.UPDATE_ERROR);
        }
    }
}
